package com.bawei.module_open.module

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.module_open.R
import java.io.File

/**
 * 视频编辑页面
 * 提供视频编辑功能，包括滤镜、水印、音频混合、文字、MV特效、贴图、涂鸦、剪辑等
 */
@Route(path = "/open/VideoEditActivity")
class VideoEditActivity : AppCompatActivity(), VideoEditCallback {
    
    private var videoPath: String? = null
    private var outputPath: String? = null
    private var draftPath: String? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video_edit)
        
        // 获取视频路径
        videoPath = intent.getStringExtra("video_path")
        if (videoPath.isNullOrEmpty()) {
            Toast.makeText(this, "视频路径无效", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        
        // 初始化路径
        initPaths()
        
        // 初始化编辑器
        if (!initEditor()) {
            Toast.makeText(this, "编辑器初始化失败", Toast.LENGTH_SHORT).show()
            finish()
            return
        }
        
        initViews()
        initVideoInfo()
    }
    
    /**
     * 初始化路径
     */
    private fun initPaths() {
        val baseDir = getExternalFilesDir(null)
        draftPath = "${baseDir}/drafts/"
        outputPath = "${baseDir}/output/"
        
        // 创建目录
        File(draftPath!!).mkdirs()
        File(outputPath!!).mkdirs()
    }
    
    /**
     * 初始化编辑器
     */
    private fun initEditor(): Boolean {
        return QiniuVideoManager.initEditor(videoPath!!, draftPath!!)
    }
    
    /**
     * 初始化视图
     */
    private fun initViews() {
        // 返回按钮
        findViewById<Button>(R.id.btn_back).setOnClickListener {
            finish()
        }
        
        // 保存按钮
        findViewById<Button>(R.id.btn_save).setOnClickListener {
            saveVideo()
        }
        
        // 编辑功能按钮
        findViewById<Button>(R.id.btn_filter).setOnClickListener {
            showFilterOptions()
        }
        
        findViewById<Button>(R.id.btn_watermark).setOnClickListener {
            showWatermarkOptions()
        }
        
        findViewById<Button>(R.id.btn_audio).setOnClickListener {
            showAudioOptions()
        }
        
        findViewById<Button>(R.id.btn_text).setOnClickListener {
            showTextOptions()
        }
        
        findViewById<Button>(R.id.btn_effects).setOnClickListener {
            showEffectsOptions()
        }
        
        findViewById<Button>(R.id.btn_stickers).setOnClickListener {
            showStickersOptions()
        }
        
        findViewById<Button>(R.id.btn_doodle).setOnClickListener {
            showDoodleOptions()
        }
        
        findViewById<Button>(R.id.btn_trim).setOnClickListener {
            showTrimOptions()
        }
    }
    
    /**
     * 初始化视频信息
     */
    private fun initVideoInfo() {
        val videoFile = File(videoPath!!)
        val fileSize = videoFile.length() / 1024 / 1024 // MB
        val duration = "未知" // 这里可以解析视频时长
        
        findViewById<TextView>(R.id.tv_video_info).text =
            "视频文件: ${videoFile.name}\n" +
            "文件大小: ${fileSize}MB\n" +
            "时长: $duration\n" +
            "编辑状态: 已初始化"
    }
    
    /**
     * 显示滤镜选项
     */
    private fun showFilterOptions() {
        val filterTypes = arrayOf("原图", "黑白", "复古", "暖色", "冷色", "高对比度", "柔和")
        
        // 这里可以显示滤镜选择对话框
        // 为了演示，直接应用第一个滤镜
        val success = QiniuVideoManager.addFilter("warm", 0.6f)
        if (success) {
            Toast.makeText(this, "滤镜已应用: 暖色", Toast.LENGTH_SHORT).show()
            updateVideoInfo("已添加暖色滤镜")
        } else {
            Toast.makeText(this, "滤镜应用失败", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 显示水印选项
     */
    private fun showWatermarkOptions() {
        // 这里可以显示水印选择对话框
        // 为了演示，直接添加一个示例水印
        val watermarkPath = "${getExternalFilesDir(null)}/watermark.png"
        
        // 创建示例水印文件（实际应用中应该从资源或用户选择）
        val success = QiniuVideoManager.addWatermark(watermarkPath, 50f, 50f, 0.5f)
        if (success) {
            Toast.makeText(this, "水印已添加", Toast.LENGTH_SHORT).show()
            updateVideoInfo("已添加水印")
        } else {
            Toast.makeText(this, "水印添加失败", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 显示音频选项
     */
    private fun showAudioOptions() {
        // 这里可以显示音频选择对话框
        // 为了演示，直接添加一个示例音频
        val audioPath = "${getExternalFilesDir(null)}/background_music.mp3"
        
        val success = QiniuVideoManager.addAudioMix(audioPath, 0.3f, 0)
        if (success) {
            Toast.makeText(this, "背景音乐已添加", Toast.LENGTH_SHORT).show()
            updateVideoInfo("已添加背景音乐")
        } else {
            Toast.makeText(this, "音频添加失败", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 显示文字选项
     */
    private fun showTextOptions() {
        // 这里可以显示文字输入对话框
        // 为了演示，直接添加示例文字
        val success = QiniuVideoManager.addText(
            text = "Hello World!",
            x = 100f,
            y = 200f,
            fontSize = 32f,
            color = 0xFFFF0000.toInt(), // 红色
            startTime = 1000,
            duration = 4000
        )
        
        if (success) {
            Toast.makeText(this, "文字已添加", Toast.LENGTH_SHORT).show()
            updateVideoInfo("已添加文字")
        } else {
            Toast.makeText(this, "文字添加失败", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 显示特效选项
     */
    private fun showEffectsOptions() {
        // 这里可以显示MV特效选择对话框
        // 为了演示，直接添加示例特效
        val success = QiniuVideoManager.addMVEffect(
            effectType = "wave",
            intensity = 0.7f,
            startTime = 2000,
            duration = 3000
        )
        
        if (success) {
            Toast.makeText(this, "MV特效已添加", Toast.LENGTH_SHORT).show()
            updateVideoInfo("已添加MV特效")
        } else {
            Toast.makeText(this, "特效添加失败", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 显示贴图选项
     */
    private fun showStickersOptions() {
        // 这里可以显示贴图选择对话框
        // 为了演示，直接添加示例贴图
        val stickerPath = "${getExternalFilesDir(null)}/sticker.png"
        
        val success = QiniuVideoManager.addSticker(
            stickerPath = stickerPath,
            x = 300f,
            y = 150f,
            scale = 0.8f,
            rotation = 15f,
            startTime = 1500,
            duration = 5000
        )
        
        if (success) {
            Toast.makeText(this, "贴图已添加", Toast.LENGTH_SHORT).show()
            updateVideoInfo("已添加贴图")
        } else {
            Toast.makeText(this, "贴图添加失败", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 显示涂鸦选项
     */
    private fun showDoodleOptions() {
        // 这里可以显示涂鸦绘制界面
        // 为了演示，直接添加示例涂鸦
        val doodlePath = "${getExternalFilesDir(null)}/doodle.png"
        
        val success = QiniuVideoManager.addDoodle(
            doodlePath = doodlePath,
            startTime = 1000,
            duration = 4000
        )
        
        if (success) {
            Toast.makeText(this, "涂鸦已添加", Toast.LENGTH_SHORT).show()
            updateVideoInfo("已添加涂鸦")
        } else {
            Toast.makeText(this, "涂鸦添加失败", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 显示剪辑选项
     */
    private fun showTrimOptions() {
        // 这里可以显示视频剪辑界面
        // 为了演示，直接剪辑视频的前5秒
        val success = QiniuVideoManager.trimVideo(0, 5000)
        
        if (success) {
            Toast.makeText(this, "视频已剪辑", Toast.LENGTH_SHORT).show()
            updateVideoInfo("已剪辑视频")
        } else {
            Toast.makeText(this, "视频剪辑失败", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 更新视频信息
     */
    private fun updateVideoInfo(editInfo: String) {
        val currentInfo = findViewById<TextView>(R.id.tv_video_info).text.toString()
        findViewById<TextView>(R.id.tv_video_info).text = "$currentInfo\n$editInfo"
    }
    
    /**
     * 保存视频
     */
    private fun saveVideo() {
        val outputFile = File(outputPath!!, "edited_video_${System.currentTimeMillis()}.mp4")
        
        Toast.makeText(this, "正在导出视频...", Toast.LENGTH_SHORT).show()
        
        // 调用七牛云 SDK 导出视频
        QiniuVideoManager.exportVideo(outputFile.absolutePath, this)
    }
    
    // VideoEditCallback 实现
    override fun onEditSuccess(outputPath: String) {
        runOnUiThread {
            Toast.makeText(this, "视频编辑完成，已保存到: $outputPath", Toast.LENGTH_LONG).show()
            
            // 通知相册更新
            val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
            intent.data = Uri.fromFile(File(outputPath))
            sendBroadcast(intent)
            
            finish()
        }
    }
    
    override fun onEditCancel() {
        runOnUiThread {
            Toast.makeText(this, "编辑已取消", Toast.LENGTH_SHORT).show()
            finish()
        }
    }
    
    override fun onSaveDraft() {
        runOnUiThread {
            val success = QiniuVideoManager.saveDraft()
            if (success) {
                Toast.makeText(this, "草稿已保存", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "草稿保存失败", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    override fun onError(error: String) {
        runOnUiThread {
            Toast.makeText(this, "编辑失败: $error", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 释放编辑器资源
        QiniuVideoManager.releaseEditor()
    }
} 